﻿using MyModels.Models;
using MyRepository.BASE;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyRepository
{
    public class RoleModulePermissionRepository : BaseRepository<RoleModulePermission>, IRoleModulePermissionRepository
    {
        public RoleModulePermissionRepository(ISqlSugarClient sqlSugarClient) : base(sqlSugarClient)
        {

        }

        /// <summary>
        /// 查出 角色 - 菜单 - 接口关系表全部map属性数据
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleModulePermission>> GetRMPMaps()
        {
            return await Db.Queryable<RoleModulePermission>()
                .Mapper(rmp => rmp.Modules, rmp => rmp.ModuleId)
                .Mapper(rmp => rmp.Permission, rmp => rmp.PermissionId)
                .Mapper(rmp => rmp.Role, rmp => rmp.RoleId)
                .Where(d => d.IsDeleted == false)
                .ToListAsync();
        }

        /// <summary>
        /// 角色权限Map
        /// </summary>
        /// <returns></returns>
        public async Task<List<RoleModulePermission>> RoleModuleMaps()
        {
            return await QueryMuch<RoleModulePermission, Modules, Role, RoleModulePermission>(
                    (rmp, m, r) => new object[]
                    {
                        JoinType.Left,rmp.ModuleId==m.Id,
                        JoinType.Left,rmp.RoleId == r.Id
                    },
                    (rmp, m, r) => new RoleModulePermission
                    {
                        Role = r,
                        Modules = m,
                        IsDeleted = rmp.IsDeleted
                    },
                    (rmp, m, r) => rmp.IsDeleted == false && m.IsDeleted == false && r.IsDeleted == false
                    );

        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="permissionId"></param>
        /// <param name="moduleId"></param>
        /// <returns></returns>
        public async Task UpdateModuleId(long permissionId, long moduleId)
        {
            await Db.Updateable<RoleModulePermission>(i => i.ModuleId == moduleId)
                .Where(i => i.PermissionId == permissionId).ExecuteCommandAsync();
        }
    }
}
